# Obtain command line arguments from .sh file

args=(commandArgs(TRUE))

# Evaluate the arguments for use in this script

for(i in 1:length(args)) 
	
	{
		
	eval(parse(text=args[[i]]))
 
	}
	
# Establish directories
# NB BRT Source Functions must be located in the working directory

in.dir = '/home1/99/jc152199/brt/data/'
setwd(in.dir)
maxout.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/max/'
minout.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/min/'


# Load the gbm library to perform Boosted Regression Tree Analysis

library('gbm')
library('SDMTools')

# Load source code for BRT functions

source('brt.functions.R.cjsedit.r')

# Load BRT models

load('/home1/99/jc152199/brt/FINALOPTIMALMODELS/OptimalMaxModel.Rdata') ### Object will be called max.brt.gbm.step
load('/home1/99/jc152199/brt/FINALOPTIMALMODELS/OptimalMinModel.Rdata') ### Object will be called min.brt.gbm.step

# Location of static ascii files

static.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/STATIC/'

# Names of static ASCII files

static.files = list.files(static.dir,pattern='.asc',full.names=T)[c(1,3:8)]
static.files = static.files[c(5,2,6,4,3,7,1)]

# Needs to include the changing tmax and tmin file

var.names = c(min.brt.gbm.step$var.names)

# Names of all ASCII files to be read in (in the same order as var.names)

tobescanned = c(static.files[1:4],tmax.file,tmin.file,insol.file,static.files[5:7])

# This loop scans in each ASCII file (skipping the first 6 lines) and assigns it a name based on the vector 'variable.names'

predict.data = NULL

for(i in c(1:10))
	
	{
	
	assign(var.names[i],scan(tobescanned[i], skip=6, na.string = "-9999"),pos=1)
	
	cat(var.names[i],'\n')
	
	#if(length(grep('.asc.gz',asc))==1){t.asc = read.asc.gz(paste(asc,sep=''))}
	
	#if(length(grep('.asc.gz',asc))==0) {t.asc = read.asc(paste(asc,sep=''))}
	
	#t.vec = rev(as.vector(t.asc))
	
	#predict.data = cbind(predict.data,t.vec)

	}

# Bind all the grid data into a single dataframe
	
#predict.data = data.frame(predict.data)
predict.data = data.frame(lat,d2c,d2s,fpc,AWAPmax,AWAPmin,insol,dem,slope,aspect)

# Change column names in predict.data

#names(predict.data) = paste(var.names)

# Remove rows where static layers are all NA

predict.data = predict.data[which(is.na(predict.data$dem)==F),]
	
# Run the spatial prediction function

gbm.predict.grids(max.brt.gbm.step, predict.data, want.grids = T, sp.name = paste('tmax.',substr(tmax.file,75,82),sep=''),pred.vec = rep(-9999,1757400), filepath = paste(maxout.dir,substr(tmax.file,75,78),'/',sep=''), num.col = 1010, num.row = 1740, xll = 144.71, yll = -19.77151, cell.size = 0.0025, no.data = -9999)
gbm.predict.grids(min.brt.gbm.step, predict.data, want.grids = T, sp.name = paste('tmin.',substr(tmin.file,75,82),sep=''),pred.vec = rep(-9999,1757400), filepath = paste(minout.dir,substr(tmin.file,75,78),'/',sep=''), num.col = 1010, num.row = 1740, xll = 144.71, yll = -19.77151, cell.size = 0.0025, no.data = -9999)

# Read in the spatial predictions

tmax.asc = read.asc(paste(maxout.dir,substr(tmax.file,75,78),'/','tmax.',substr(tmax.file,75,82),'.asc',sep='')) # Read in ASCII prediction
tmin.asc = read.asc(paste(minout.dir,substr(tmin.file,75,78),'/','tmin.',substr(tmin.file,75,82),'.asc',sep='')) # Read in ASCII prediction

# Convert spatial predictions to .asc.gz to save space

write.asc.gz(tmax.asc, file=paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/maxgzip/',substr(tmax.file,75,78),'/','tmax.',substr(tmax.file,75,82),sep='')) # Write gzip file of ASCII prediction
write.asc.gz(tmin.asc, file=paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/mingzip/',substr(tmin.file,75,78),'/','tmin.',substr(tmin.file,75,82),sep='')) # Write gzip file of ASCII prediction

# Remove the original .asc versions of the spatial preds

if (file.exists(paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/maxgzip/',substr(tmax.file,75,78),'/','tmax.',substr(tmax.file,75,82),'.asc.gz',sep='')))
{system(paste('rm ',maxout.dir,substr(tmax.file,75,78),'/','tmax.',substr(tmax.file,75,82),'.asc',sep=''))}

if (file.exists(paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/mingzip/',substr(tmin.file,75,78),'/','tmin.',substr(tmin.file,75,82),'.asc.gz',sep='')))
{system(paste('rm ',minout.dir,substr(tmin.file,75,78),'/','tmin.',substr(tmin.file,75,82),'.asc',sep=''))}

# Done
################################################################


